package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.concurrent.CompletableFuture;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Override
    @SneakyThrows
    public String imageUpload(MultipartFile file) {

        BufferedImage read = ImageIO.read(file.getInputStream());
        if (read == null) {
            throw new GuiguException(500, "图片格式非法！");
        }

        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        }

        String folderName = "/" + DateUtil.today() + "/"; //创建文件夹,以当天日期命名,方便管理(以天为单位)
        String uuid = IdUtil.randomUUID();
        String extedName = FileUtil.extName(file.getOriginalFilename());
        String fileName = folderName + uuid + "." + extedName;

        //  http://192.168.254.156:9000/glsx/2025-06-15/174da71e-4021-4969-bebb-d620852c1681.png
        String fileUrl = minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + fileName;
        //  流上传
       minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioConstantProperties.getBucketName())
                        .object(fileName)
                        .stream(file.getInputStream(),file.getSize(),-1)
                        .contentType(file.getContentType())
                        .build());
        return fileUrl;
    }
}
